<template>
	<div>123123123</div>
	<!-- <el-dialog :title="dialogTitle" :visible.sync="visible" width="720px">
		<el-form
			ref="form"
			size="medium"
			:model="formData"
			:rules="formRules"
			v-loading="loading"
			label-width="105px"
			:validate-on-rule-change="false"
			class="principal_schedule_form"
		>
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="实验时间" prop="time">
						<el-date-picker
							v-model="formData.year"
							type="year"
							value-format="yyyy"
							placeholder="选择年"
							style="width: 110px"
							@change="handleYearChange"
						></el-date-picker>
						<el-select v-model="formData.weekCount" placeholder="选择周次" style="width: 110px" @change="handleWeekChange">
							<el-option v-for="(item, index) in weekCountData" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>
						<el-date-picker v-model="formData.startTime" type="date" placeholder="开始时间" readonly style="width: 150px"></el-date-picker>
						<span class="seq">-</span>
						<el-date-picker v-model="formData.endTime" type="date" placeholder="结束时间" readonly style="width: 150px"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="实验站" prop="expName">
						<el-select v-model="formData.expName" placeholder="选择实验站" style="width: 100%">
							<el-option v-for="(item, index) in experimentalStationData" :key="index" :label="item" :value="item"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="房间" prop="room" label-width="60px">
						<el-input v-model="formData.room" placeholder="请输入实验名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="负责人" prop="headName">
						<el-input v-model="formData.headName" placeholder="输入负责人" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="课题名称" prop="name">
						<template v-if="!!expId">
							<el-input v-model="formData.name" placeholder="请输入课题名称" readonly></el-input>
						</template>
						<template v-else>
							<el-autocomplete
								v-model="formData.name"
								value-key="name"
								placeholder="请输入课题名称"
								:fetch-suggestions="queryProjectSuggestions"
								@select="handleSelectProject"
								@change="handleChangeProject"
							></el-autocomplete>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="用户单位" prop="source">
						<el-input v-model="formData.source" placeholder="请输入用户单位" :readonly="!!expId"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户" prop="userName">
						<el-input v-model="formData.userName" placeholder="请输入用户" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="机时" prop="machineHour" label-width="60px">
						<el-input-number v-model="formData.machineHour" controls-position="right" placeholder="请输入机时"></el-input-number>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="液氦预约量" prop="filed1">
						<el-input-number v-model="formData.filed1" controls-position="right" placeholder="请输入液氦预约量"></el-input-number>
						<span class="unit">升(L)</span>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" @click="handleSubmitForm()" :loading="btnLoading">确定</el-button>
		</template>
	</el-dialog> -->
</template>

<script>
import moment from 'moment';
import { mapGetters } from 'vuex';
import { getUserList } from '@/api/system/tbSysUser';
import { queryAuditPageList } from '@/api/business/tbTopic';
import { experimentDetail } from '@/api/business/tbExperiment';
import { piStatDetail, addedPiStat, updatePiStat } from '@/api/business/tbPiStat';
export default {
	props: {
		value: { type: Boolean, default: false },
		dataId: { type: String, default: '' },
		expId: { type: String, default: '' }
	},
	data() {
		const validateTime = (rule, value, callback) => {
			let { year, weekCount } = this.formData;
			if (!year) {
				return callback(new Error('请选择实验年份'));
			} else if (!weekCount) {
				return callback(new Error('请选择实验周次'));
			} else {
				callback();
			}
		};
		return {
			visible: this.value,
			loading: false,
			formData: {},
			formRules: {
				time: [
					{ required: true, message: '请选择实验时间', trigger: 'change' },
					{ validator: validateTime, trigger: 'change' }
				],
				expName: { required: true, message: '请选择实验站', trigger: 'change' },
				room: { required: true, message: '请输入房间', trigger: 'blur' },
				headName: { required: true, message: '请输入负责人', trigger: 'blur' },
				name: { required: true, message: '请输入课题名称', trigger: ['blur', 'change'] },
				source: { required: true, message: '请输入用户单位', trigger: 'blur' },
				machineHour: { required: true, message: '请输入机时', trigger: 'blur' },
				filed1: { required: true, message: '请输入液氦预约量', trigger: 'blur' }
			},
			btnLoading: false
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		addOrEdit() {
			return !this.dataId;
		},
		dialogTitle() {
			return this.addOrEdit ? '添加实验安排' : '修改实验安排';
		},
		weekCountData() {
			let arr = [];
			for (let i = 0; i < 52; i++) {
				arr.push({ label: `第 ${i + 1} 周`, value: i + 1 });
			}
			return arr;
		},
		experimentalStationData() {
			let arr = [];
			for (let i = 0; i < 52; i++) {
				arr.push(`实验站 ${i + 1} 号`);
			}
			return arr;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible: {
			async handler(flag) {
				this.$emit('input', flag);
				if (!flag) return false;
				this.loading = true;
				if (this.addOrEdit) {
					let datas = { headId: this.userInfo.id, headName: this.userInfo.username };
					if (!this.expId) {
						this.formData = { ...datas };
					} else {
						let topic = await this.getExperimentData(this.expId);
						this.formData = { ...datas, ...topic };
					}
				} else {
					this.formData = await this.getDataDetail();
				}
				this.$nextTick(() => {
					this.$refs['form'].clearValidate();
				});
				this.loading = false;
			},
			immediate: true
		},
		'formData.year': {
			handler(val) {
				if (!val && !this.formData.weekCount) {
					this.$delete(this.formData, 'time');
				} else {
					this.$set(this.formData, 'time', 'time');
				}
			}
		},
		'formData.weekCount': {
			handler(val) {
				if (!val && !this.formData.year) {
					this.$delete(this.formData, 'time');
				} else {
					this.$set(this.formData, 'time', 'time');
				}
			}
		}
	},
	methods: {
		//获取实验详情
		async getExperimentData(id) {
			let result = await experimentDetail(id).then((res) => res.data);
			if (result.code === '0') {
				let datas = !!result.data && result.data.length > 0 ? result.data[0] : {};
				let topicData = datas.topic || {};
				let userData = datas.user || {};
				return Promise.resolve({ name: topicData.name, machineHour: datas.machineHour, userName: datas.createName, source: userData.filed2 });
			}
		},

		//获取数据详情
		async getDataDetail() {
			let result = await piStatDetail(this.dataId).then((res) => res.data);
			if (result.code === '0') {
				let datas = !!result.data && result.data.length > 0 ? result.data[0] : {};
				return Promise.resolve(datas);
			}
		},

		//年变化
		handleYearChange(value) {
			if (!!this.formData.weekCount && !!value) {
				this.getStartEndTime(this.formData);
			}
		},

		//周次变化
		handleWeekChange(value) {
			if (!!this.formData.year && !!value) {
				this.getStartEndTime(this.formData);
			}
		},

		//获取开始结束时间
		getStartEndTime(data) {
			let week = Number(data.weekCount);
			let year = moment().year(Number(data.year));
			let startTime = year.isoWeek(week).startOf('isoWeek');
			let endTime = moment(startTime).add(6, 'days');
			this.$set(this.formData, 'startTime', startTime.format('YYYY-MM-DD'));
			this.$set(this.formData, 'endTime', endTime.format('YYYY-MM-DD'));
		},

		//查询用户数据
		async queryUserSuggestions(value, cb) {
			let params = { page: 1, limit: 99999, userName: value };
			let result = await getUserList(params).then((res) => res.data);
			if (result.code === '0') {
				cb(result.data || []);
			}
		},

		//查询课题数据
		async queryProjectSuggestions(value, cb) {
			let params = { page: 1, limit: 99999, audit: '1', name: value };
			let result = await queryAuditPageList(params).then((res) => res.data);
			if (result.code === '0') {
				cb(result.data || []);
				this.projectListData = result.data || [];
			}
		},

		//选择课题
		handleSelectProject(data) {
			this.$set(this.formData, 'name', data.name);
			this.$set(this.formData, 'userId', data.createId);
			this.$set(this.formData, 'userName', data.createName);
		},

		//课题变化
		handleChangeProject(name) {
			this.$set(this.formData, 'name', name);
			queryTopicPageList({ page: 1, limit: 10, name }).then((res) => {
				let result = res.data;
				if (result.code === '0') {
					let datas = result.data || [];
					if (datas.length > 0) {
						this.$set(this.formData, 'userId', datas[0].createId);
						this.$set(this.formData, 'userName', datas[0].createName);
					} else {
						this.$set(this.formData, 'userId', this.userInfo.id);
						this.$set(this.formData, 'userName', this.userInfo.username);
					}
				}
			});
		},

		//选择负责人
		handleSelectLeader(data) {
			this.$set(this.formData, 'headId', data.id);
			this.$set(this.formData, 'headName', data.userName);
		},

		//提交
		handleSubmitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				this.submitFormRequest();
			});
		},

		//提交表单请求
		async submitFormRequest() {
			let params = { ...this.formData };
			let callFunction = eval(this.addOrEdit ? addedPiStat : updatePiStat);
			let result = await callFunction(params).then((res) => res.data);
			this.btnLoading = false;
			if (result.code === '0') {
				this.$showCustomMessage('success', `${this.addOrEdit ? '添加' : '修改'}数据成功`);
				this.visible = false;
				this.$emit('finish');
			}
		}
	}
};
</script>

<style lang="scss" scoped>
:deep(.principal_schedule_form) {
	width: 100%;
	overflow: hidden;
	padding: 10px 10px 0;
	.el-form-item__label {
		font-size: 16px;
	}
	.el-form-item__content {
		display: flex;
		align-items: center;
		.unit {
			flex-shrink: 0;
			margin-left: 10px;
		}
	}
	.el-date-editor {
		font-size: 16px;
		margin-right: 10px;
		&:last-child {
			margin-right: 0;
		}
	}
	.el-select {
		font-size: 16px;
		margin-right: 10px;
		.el-input {
			width: 100%;
		}
	}
	span.seq {
		margin-right: 10px;
	}
	.el-input {
		font-size: 16px;
	}
	.is-controls-right {
		width: 100%;
	}
	.el-autocomplete {
		width: 100%;
	}
}
</style>
